﻿namespace WLFramework.Validation
{
    using System;

    [AttributeUsage(AttributeTargets.Property)]
    public class RequiredAttribute : ValidationAttribute
    {
        public RequiredAttribute() :
            this("字段'{0}'不能为空")
        { 
        }

        public RequiredAttribute(string displayErrors)
            : this(displayErrors, "请输入{0}")
        {
        }

        public RequiredAttribute(string displayErrors, string displayDefault)
        {
            this.ErrorMessage = displayErrors;
            this.DefaultMessage = displayDefault;
        }

        public override ValidatePriority Priority
        {
            get
            {
                return ValidatePriority.High;
            }
        }

        public override ValidateResult IsValid(object input, ValidateContext context)
        {
            return input != null ? ValidateResult.Success : new ValidateResult(this.FormatErrorMessage(context.DisplayName));
        }

        public override string FormatErrorMessage(string name)
        {
            return string.Format(this.ErrorMessage, name);
        }
    }
}
